package com.ysd;

import com.ysd.service.SysOptionsService;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.Map;
import java.util.Set;

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@MapperScan({"com.ysd.lis.mapper.**", "com.ysd.lis.mapper", "com.ysd.dao"})
@EnableAsync
@EnableSwagger2
@EnableScheduling
@EnableTransactionManagement
public class LisApplication {

    @Autowired
    SysOptionsService sysOptionsService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public static void main(String[] args) {
        SpringApplication.run(LisApplication.class, args);
    }

    @Bean
    public ApplicationRunner init() {
        return args -> {
            Long st = System.currentTimeMillis();
            // 1. 删除旧的 system:options: 参数
            Set<String> keysToDelete = redisTemplate.keys("system:options:*");
            if (keysToDelete != null && !keysToDelete.isEmpty()) {
                redisTemplate.delete(keysToDelete);
                System.out.println("历史系统选项已从REDIS删除");
            }

            // 获取系统选项参数
            Map<String, Map<String, String>> options = sysOptionsService.findSysParamFieldAndValueList();
            options.forEach((key, value) -> {
                String redisKey = "system:options:" + key; // 格式化 Redis Key
                value.forEach((k, v) -> {
                    redisTemplate.opsForValue().set(redisKey + ":" + k, v);
                });
            });

            Long st2 = System.currentTimeMillis();
            System.out.println("缓存系统选项共耗时:" + (st2 - st) + "ms");
        };
    }

}
